package my.senix.springfactories;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by lhs on 2018/8/15.
 */
public class MyCustomCtxInitializer
        implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final static String MY_PROPERTIES = "myProperties";

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();

        Map<String, Object> map = new HashMap<>();

        Random random = new Random();
        Integer port = random.nextInt(4000) + 30000;
//        map.put("server.port",port);
        map.put("local.server.port",6666);

        if (!environment.getPropertySources().contains("bootstrap")
            && !environment.getPropertySources().contains(MY_PROPERTIES)) {

            environment.getPropertySources().addFirst(new MapPropertySource(MY_PROPERTIES, map));
        }
    }
}
